package com.repair.system.service;

import com.repair.system.dto.CoordinateData;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
public class FileUploadService {

    // 支持的坐标文件格式
    private static final Set<String> COORDINATE_EXTENSIONS = Set.of("csv", "xy", "txt");
    private static final Set<String> IMAGE_EXTENSIONS = Set.of("jpg", "jpeg", "png");
    private static final Set<String> PDF_EXTENSION = Set.of("pdf");

    public boolean isValidCoordinateFile(String filename) {
        String extension = getFileExtension(filename).toLowerCase();
        return COORDINATE_EXTENSIONS.contains(extension);
    }

    public boolean isValidImageFile(String filename) {
        String extension = getFileExtension(filename).toLowerCase();
        return IMAGE_EXTENSIONS.contains(extension);
    }

    public boolean isValidPdfFile(String filename) {
        String extension = getFileExtension(filename).toLowerCase();
        return PDF_EXTENSION.contains(extension);
    }

    public List<CoordinateData> parseCoordinateFile(MultipartFile file) throws IOException {
        List<CoordinateData> coordinates = new ArrayList<>();
        String extension = getFileExtension(file.getOriginalFilename()).toLowerCase();

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            
            String line;
            boolean isFirstLine = true;
            
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty() || line.startsWith("#")) continue;
                
                // 跳过标题行
                if (isFirstLine && line.toLowerCase().contains("designator")) {
                    isFirstLine = false;
                    continue;
                }
                
                String[] parts = line.split("[,\\s]+");
                if (parts.length >= 3) {
                    CoordinateData data = new CoordinateData();
                    data.setDesignator(parts[0]);
                    data.setX(Double.parseDouble(parts[1]));
                    data.setY(Double.parseDouble(parts[2]));
                    data.setLayer(parts.length > 3 ? parts[3] : "Top");
                    coordinates.add(data);
                }
            }
        }
        
        return coordinates;
    }

    public String saveUploadedFile(MultipartFile file, String uploadDir) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件为空");
        }

        String filename = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        File uploadPath = new File(uploadDir);
        if (!uploadPath.exists()) {
            uploadPath.mkdirs();
        }

        File destFile = new File(uploadPath, filename);
        file.transferTo(destFile);
        
        return filename;
    }

    private String getFileExtension(String filename) {
        if (filename == null || !filename.contains(".")) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    public Map<String, Object> getFileInfo(String filename, String fileType) {
        Map<String, Object> info = new HashMap<>();
        info.put("filename", filename);
        info.put("type", fileType);
        info.put("uploadTime", new Date());
        info.put("size", "待计算");
        return info;
    }
}
